package com.example.pceb.component;

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.ConcurrentHashMap;

public class SignalWebSocketHandler extends TextWebSocketHandler {

    // 房间内用户连接映射，roomId -> username -> session
    private static final ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketSession>> roomSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String roomId = getQueryParam(session, "roomId");
        String username = getQueryParam(session, "username");
        roomSessions.putIfAbsent(roomId, new ConcurrentHashMap<>());
        roomSessions.get(roomId).put(username, session);
        System.out.println("[WS] 用户连接: roomId=" + roomId + ", username=" + username);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload(); // JSON 字符串
        String roomId = getQueryParam(session, "roomId");
        String fromUser = getQueryParam(session, "username");

        // 简单判断消息类型
        if (payload.contains("\"type\":\"danmu\"")) {
            // 弹幕消息，广播给房间内所有人（包括自己）
            ConcurrentHashMap<String, WebSocketSession> users = roomSessions.getOrDefault(roomId, new ConcurrentHashMap<>());
            for (WebSocketSession targetSession : users.values()) {
                if (targetSession != null && targetSession.isOpen()) {
                    targetSession.sendMessage(new TextMessage(payload));
                }
            }
            System.out.println("[WS] 弹幕广播: roomId=" + roomId + ", from=" + fromUser + ", 内容=" + payload);
            return;
        }

        // 解析 to 字段（用于一对多定向信令）
        String toUser = null;
        if (payload.contains("\"to\"")) {
            // 简单解析 to 字段
            int idx = payload.indexOf("\"to\"");
            int start = payload.indexOf("\"", idx + 4) + 1;
            int end = payload.indexOf("\"", start);
            if (start > 0 && end > start) {
                toUser = payload.substring(start, end);
            }
        }

        if (toUser != null && !toUser.isEmpty()) {
            // 定向消息，只发给指定用户
            WebSocketSession targetSession = roomSessions.getOrDefault(roomId, new ConcurrentHashMap<>()).get(toUser);
            if (targetSession != null && targetSession.isOpen()) {
                targetSession.sendMessage(new TextMessage(payload));
                System.out.println("[WS] 定向消息: " + fromUser + " -> " + toUser + " 内容=" + payload);
            }
        } else {
            // 普通信令，转发给房间内除自己外所有人
            for (String user : roomSessions.getOrDefault(roomId, new ConcurrentHashMap<>()).keySet()) {
                if (!user.equals(fromUser)) {
                    WebSocketSession targetSession = roomSessions.get(roomId).get(user);
                    if (targetSession != null && targetSession.isOpen()) {
                        targetSession.sendMessage(new TextMessage(payload));
                    }
                }
            }
            System.out.println("[WS] 普通信令: " + fromUser + " -> 房间其他人, 内容=" + payload);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String roomId = getQueryParam(session, "roomId");
        String username = getQueryParam(session, "username");
        roomSessions.getOrDefault(roomId, new ConcurrentHashMap<>()).remove(username);
        System.out.println("[WS] 用户断开: roomId=" + roomId + ", username=" + username);
    }

    private String getQueryParam(WebSocketSession session, String key) {
        String query = session.getUri().getQuery();
        if (query == null) return "";
        for (String pair : query.split("&")) {
            String[] kv = pair.split("=", 2);
            if (kv.length == 2 && kv[0].equals(key)) {
                return kv[1];
            }
        }
        return "";
    }
}